package liangtWorkSpace.threadDemo.thread.JUC;

import lombok.SneakyThrows;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author liangt
 * @ClassName: SemephoreSimple
 * @title: SemephoreSimple
 * @projectName liangtWorkSpace.threadDemo.thread.JUC
 * @description: 信号量，限制线程数，当线程数达到信号量时，将阻塞多余线程，等待信号量释放之后重新调用
 * @date 2020/11/5 18:49
 */
public class SemephoreSimple {
    public static void main(String[] args) {

        ExecutorService threadPools = Executors.newFixedThreadPool(20);
        //设置信号量
        Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 20; i++) {
            threadPools.execute(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    try {
                        semaphore.acquire();//占用信号量
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    play();
                    semaphore.release();//释放信号量
                }
            });
        }
        threadPools.shutdown();
    }

    public static void play() throws InterruptedException {
        System.out.println(new Date() + ":" +Thread.currentThread().getName() + ":获取服务器");
        Thread.sleep(2000);
        System.out.println(new Date() + ":" +Thread.currentThread().getName() + "退出服务器");
        Thread.sleep(500);
    }
}
